package com.phiture.erp.stock.web.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.phiture.erp.basic.api.pojo.resp.ErpCustomerResp;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialInfoResp;
import com.phiture.erp.basic.api.service.ErpCustomerApi;
import com.phiture.erp.basic.api.service.ErpMaterialApi;
import com.phiture.erp.stock.core.pojo.dto.ErpStockOutPageReqDTO;
import com.phiture.erp.stock.core.pojo.dto.ErpStockOutSaveReqDTO;
import com.phiture.erp.stock.core.pojo.vo.ErpStockOutRespVO;
import com.phiture.erp.stock.core.service.ErpStockOutReqService;
import com.phiture.erp.stock.core.service.ErpStockService;
import com.phiture.erp.stock.dal.entity.ErpStockDO;
import com.phiture.erp.stock.dal.entity.ErpStockOutDO;
import com.phiture.erp.stock.dal.entity.ErpStockOutItemDO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMultiMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

@Tag(name = "管理后台 - ERP 领料出库单")
@RestController
@RequiredArgsConstructor
@RequestMapping("/erp/stock-out-req")
public class ErpStockOutReqController {
    private final ErpStockOutReqService stockOutReqService;
    private final ErpStockService stockService;
    private final ErpMaterialApi materialApi;
    private final DeptApi deptApi;
    private final AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建领料出库单")
    @PreAuthorize("@ss.hasPermission('erp:stock-out:create')")
    public CommonResult<Long> createStockOut(@Valid @RequestBody ErpStockOutSaveReqDTO createReqDTO) {
        return success(stockOutReqService.createStockOut(createReqDTO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新领料出库单")
    @PreAuthorize("@ss.hasPermission('erp:stock-out:update')")
    public CommonResult<Boolean> updateStockOut(@Valid @RequestBody ErpStockOutSaveReqDTO updateReqDTO) {
        stockOutReqService.updateStockOut(updateReqDTO);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新领料出库单的状态")
    @PreAuthorize("@ss.hasPermission('erp:stock-out:update-status')")
    public CommonResult<Boolean> updateStockOutStatus(@RequestParam("id") Long id,
                                                     @RequestParam("status") Integer status) {
        stockOutReqService.updateStockOutStatus(id, status);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除领料出库单")
    @Parameter(name = "ids", description = "编号数组", required = true)
    @PreAuthorize("@ss.hasPermission('erp:stock-out:delete')")
    public CommonResult<Boolean> deleteStockOut(@RequestParam("ids") List<Long> ids) {
        stockOutReqService.deleteStockOut(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得领料出库单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:stock-out:query')")
    public CommonResult<ErpStockOutRespVO> getStockOut(@RequestParam("id") Long id) {
        ErpStockOutDO stockOut = stockOutReqService.getStockOut(id);
        if (stockOut == null) {
            return success(null);
        }
        List<ErpStockOutItemDO> stockOutItemList = stockOutReqService.getStockOutItemListByOutId(id);
        Map<Long, ErpMaterialInfoResp> productMap = materialApi.getMaterialMap(
                convertSet(stockOutItemList, ErpStockOutItemDO::getMaterialId));
        return success(BeanUtils.toBean(stockOut, ErpStockOutRespVO.class, stockOutVO ->
                stockOutVO.setItems(BeanUtils.toBean(stockOutItemList, ErpStockOutRespVO.Item.class, item -> {
                    ErpStockDO stock = stockService.getStock(item.getMaterialId(), item.getWarehouseId());
                    item.setStockCount(stock != null ? stock.getCount() : BigDecimal.ZERO);
                    MapUtils.findAndThen(productMap, item.getMaterialId(), product -> item.setMaterialName(product.getName())
                            .setMaterialBarCode(product.getBarCode()).setMaterialUnitName(product.getUnitName()));
                }))));
    }

    @GetMapping("/page")
    @Operation(summary = "获得领料出库单分页")
    @PreAuthorize("@ss.hasPermission('erp:stock-out:query')")
    public CommonResult<PageResult<ErpStockOutRespVO>> getStockOutPage(@Valid ErpStockOutPageReqDTO pageReqDTO) {
        PageResult<ErpStockOutDO> pageResult = stockOutReqService.getStockOutPage(pageReqDTO);
        return success(buildStockOutVOPageResult(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出领料出库单 Excel")
    @PreAuthorize("@ss.hasPermission('erp:stock-out:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportStockOutExcel(@Valid ErpStockOutPageReqDTO pageReqDTO,
              HttpServletResponse response) throws IOException {
        pageReqDTO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ErpStockOutRespVO> list = buildStockOutVOPageResult(stockOutReqService.getStockOutPage(pageReqDTO)).getList();
        // 导出 Excel
        ExcelUtils.write(response, "领料出库单.xls", "数据", ErpStockOutRespVO.class, list);
    }

    private PageResult<ErpStockOutRespVO> buildStockOutVOPageResult(PageResult<ErpStockOutDO> pageResult) {
        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }
        // 1.1 出库项
        List<ErpStockOutItemDO> stockOutItemList = stockOutReqService.getStockOutItemListByOutIds(
                convertSet(pageResult.getList(), ErpStockOutDO::getId));
        Map<Long, List<ErpStockOutItemDO>> stockOutItemMap = convertMultiMap(stockOutItemList, ErpStockOutItemDO::getOutId);
        // 1.2 物料信息
        Map<Long, ErpMaterialInfoResp> materialMap = materialApi.getMaterialMap(
                convertSet(stockOutItemList, ErpStockOutItemDO::getMaterialId));
        // 1.3 部门信息
        Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMap(
                convertSet(pageResult.getList(), ErpStockOutDO::getCustomerId));
        // 1.4 管理员信息
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(pageResult.getList(), stockOut -> Long.parseLong(stockOut.getCreator())));
        // 2. 开始拼接
        return BeanUtils.toBean(pageResult, ErpStockOutRespVO.class, stockOut -> {
            stockOut.setItems(BeanUtils.toBean(stockOutItemMap.get(stockOut.getId()), ErpStockOutRespVO.Item.class,
                    item -> MapUtils.findAndThen(materialMap, item.getMaterialId(), material -> item.setMaterialName(material.getName())
                            .setMaterialBarCode(material.getBarCode()).setMaterialUnitName(material.getUnitName()))));
            stockOut.setMaterialNames(CollUtil.join(stockOut.getItems(), "，", ErpStockOutRespVO.Item::getMaterialName));
            MapUtils.findAndThen(deptMap, stockOut.getCustomerId(), dept -> stockOut.setCustomerName(dept.getName()));
            MapUtils.findAndThen(userMap, Long.parseLong(stockOut.getCreator()), user -> stockOut.setCreatorName(user.getNickname()));
        });
    }

}